package cn.nawang.ebeim.test.handler;

import cn.nawang.ebeim.test.annotation.Column;

import java.lang.reflect.Field;
import java.sql.ResultSet;

/**
 * Created with IntelliJ IDEA.
 * User: 甘竞存
 * Date: 14-11-10
 * Time: 上午10:53
 * 处理结果集返回单个bean对象
 */
public class BeanHandler implements ResultSetHandler {

    private final Class clazz;

    public BeanHandler(Class clazz){
        this.clazz = clazz;
    }

    @Override
    public Object handler(ResultSet rs) {
        try {
            if (!rs.next()) {
                return null;
            }
            Object bean = clazz.newInstance();
            //得到bean的所有字段
            Field[] declaredFields = clazz.getDeclaredFields();
            for (int i = 0; i < declaredFields.length; i++) {
                Field field = declaredFields[i];
                Column annotation = field.getAnnotation(Column.class);
                String columnName = annotation.value();
                Object value = rs.getObject(columnName);
                field.setAccessible(true);
                field.set(bean,value);
            }
            return bean;

        } catch (Exception e) {
            // 再次抛出异常，让上一级去处理
            throw new RuntimeException(e);
        }
    }

}
